# $Id: views.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

# Create your views here.

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import render_to_response

from djanet import utils
from djanet.lib import exception
from djanet.termserver import forms, models
from djanet.utils import http
from djanet.utils import grid

@login_required
def csmapping(request):
   log = utils.loghandle(csmapping.__name__)
   csform = None
   retval = None
   if request.method == 'GET':
      csform = forms.ConsoleForm()
      csgrid = None
      try:
         csgrid = grid.ModelGrid('termserver', 'consoleserver')
      except exception.GridError, message:
         raise Http404
      else:
         retval = render_to_response(settings.TEMPLATES['CSMAPPING'],
               utils.get_context(request, csform = csform,
                  csform_action = reverse(csmapping), title = 'csmapping',
                  csform_title = 'Add console server',
                  css_url = settings.DOJO_XD_URL, tlayout = csgrid.grid.layout))
   elif request.method == 'POST':
      retval = {}
      conserver = models.ConsoleServer(updated_user = request.user)
      csform = forms.ConsoleForm(request.POST, instance = conserver)
      if csform.is_valid():
         temp = None
         try:
            temp = models.ConsoleServer.objects.get(
                  console_server = request.POST['console_server'])
         except ObjectDoesNotExist, message:
            csform.save()
            retval['message'] = "Added console server %s" %conserver
         else:
            retval['message'] = "'%s' console server exists in db" %temp

         retval['success'] = True
         retval = http.JSONResponse(retval)
         log(str(retval))
      else:
         retval['message'] = 'Invalid form entry'
         retval = http.JSONResponse(retval)
   else:
      raise Http404

   return retval
